package com.nowcoder.chapter3.part37;

import java.util.Comparator;
import java.util.TreeMap;

/**
 * TreeMap
 */
public class MapDemo4 {

    public static void main(String[] args) {
        TreeMap map = null;

        // 自然排序
        map = new TreeMap();
        map.put("Lily", 90);
        map.put("Mary", 80);
        map.put("John", 70);
        map.put("Lucy", 60);
        map.put("Tony", 50);
        map.put("Lisa", 40);
        System.out.println(map);

        System.out.println(map.firstKey() + ", " + map.lastKey());
        System.out.println(map.lowerKey("Lucy") + ", " + map.higherKey("Lucy"));
        System.out.println(map.headMap("Lucy"));
        System.out.println(map.tailMap("Lucy"));
        System.out.println(map.subMap("Lily", "Mary"));

        // 定制排序
        map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                String s1 = (String) o1;
                String s2 = (String) o2;
                if (s1 == null && s2 == null) {
                    return 0;
                } else if (s1 == null) {
                    return 1;
                } else if (s2 == null) {
                    return -1;
                } else {
//                    return s1.compareTo(s2) * (-1);
                    return s2.compareTo(s1);
                }
            }
        });

        map.put("Lily", 90);
        map.put("Mary", 80);
        map.put("John", 70);
        map.put("Lucy", 60);
        map.put("Tony", 50);
        map.put("Lisa", 40);
        System.out.println(map);
    }

}
